<?php
/**
 * Created by PHPStorm
 * User: xiest
 * Date: 2021/6/8
 * Email: <939369942@qq.com>
 */
namespace app\controller\admin;

use app\BaseController;
use app\common\repositories\group\GroupRepository;
use app\common\repositories\order\OrderRepository;
use app\common\repositories\system\SystemConfigValueRepository;
use app\common\repositories\system\SystemSwiperRepository;
use app\common\repositories\system\SystemVisitRecordRepository;
use app\common\repositories\user\UserRepository;
use app\common\repositories\user\UserViewRepository;
use basic\services\MiniProgramService;
use basic\services\UploadService;
use think\App;
use think\exception\ValidateException;
use think\facade\Cache;
use think\facade\Config;
use think\facade\Log;

class Common extends BaseController{

    public function __construct(App $app)
    {
        parent::__construct($app);
    }


    public function upload($field,$type = '')
    {
        $file = $this->request->file($field);
        if (!$file)
            return app('json')->fail('请上传附件');
        $upload = UploadService::create($type);
        $data = $upload->toPath('attach')->validateStatus(false)->move($field);
        if ($data === false) {
            return app('json')->fail($upload->getError());
        }
        $res = $upload->getUploadInfo();
        $res['dir'] = path_to_url($res['dir']);
        return app('json')->success(['src' => env('SITE_URL').$res['dir']]);
    }


    /**
     * 登录数据
     * @return mixed
     * User: xiest
     * Date: 2021/12/15
     */
    public function loginConfig()
    {
        $data = systemConfig(['site_name','site_logo']);
        return success($data);
    }



    public function systemSetting()
    {
        $params = $this->request->params([
            'user_can_publish_ad',
            'need_to_publish_ad_count',
            'watch_ad_get_money_time',
            'day_can_share_count',
        ]);


        validate([
            'user_can_publish_ad|用户是否可以发布广告'=>'require|number',
            'need_to_publish_ad_count|获取收益前需要发布广告的条数'=>'require|number',
            'watch_ad_get_money_time|浏览广告有效时间'=>'require|number',
            'day_can_share_count|每日最多分享广告次数'=>'require|number',
        ])->check($params);

        app()->make(SystemConfigValueRepository::class)->setFormData($params,'admin');
        return success('保存成功');
    }


    public function getSystemSetting()
    {
        $keys = [
            'user_can_publish_ad',
            'need_to_publish_ad_count',
            'watch_ad_get_money_time',
            'day_can_share_count',
        ];

        $arr = [];
        foreach ($keys as $key){
            $arr[$key] = systemConfig($key);
        }

        return success($arr);
    }




    public function agreementSetting()
    {
        $content = input('content');
        $type = input('type');
        if(!$type)
            return fail('类型错误');
        app()->make(SystemConfigValueRepository::class)->setFormData(['agree_'.$type=>$content],'admin');
        return success('保存成功');
    }


    public function getAgreement()
    {
        $type = input('type');
        $arr = getAgreementArr();
        return success(['name'=>$arr[$type] ?? '','content'=>systemConfig('agree_'.$type)]);
    }


    public function sysSetting()
    {
        $params = $this->request->params([
            'user_can_free_count',
            'share_user_free_count',
            'member_brokerage_percent',
            'lawyer_income_percent',
            'extract_fee'
        ]);

        validate([
            'user_can_free_count|用户免费提问次数'=>'require|number',
            'share_user_free_count|邀请用户获得免费提问次数'=>'require|number',
            'member_brokerage_percent|会员分佣比例'=>'require',
            'lawyer_income_percent|律师收入比例'=>'require',
            'extract_fee|提现手续费比例'=>'require',
        ])->check($params);

        if($params['member_brokerage_percent'] > 0.5)
            throw new ValidateException('会员分佣比例不能大于0.5');


        if($params['member_brokerage_percent'] < 0 || $params['member_brokerage_percent'] > 1)
            throw new ValidateException('律师收入比例应该在0-1之间');

        if($params['extract_fee'] < 0 || $params['extract_fee'] > 0.2)
            throw new ValidateException('提现手续费比例应该在0-0.2之间');

        app()->make(SystemConfigValueRepository::class)->setFormData($params,'admin');
        return success('保存成功');
    }


    public function getSysSetting()
    {
        $keys = [
            'user_can_free_count',
            'share_user_free_count',
            'member_brokerage_percent',
            'lawyer_income_percent',
            'extract_fee'
        ];

        $arr = [];
        foreach ($keys as $key){
            $arr[$key] = systemConfig($key);
        }

        return success($arr);
    }

    public function setMaterial()
    {
        $mainDo = input('data');
        if(!is_array($mainDo) || !count($mainDo)){
            throw new ValidateException('请添加扩展类型');
        }


        foreach ($mainDo as $item) {
            if(!isset($item['title']) || !$item['title'])
                throw new ValidateException('请完善扩展类型名称');

            if(!isset($item['value']) || !is_array($item['value']) || !count($item['value']))
                throw new ValidateException('请完善扩展类型内容');
        }



        app()->make(SystemConfigValueRepository::class)->setFormData(['sys_material_lst'=>json_encode($mainDo)],'admin');
        return success('保存成功');
    }


    public function getMaterial()
    {
        $data = json_decode(systemConfig('sys_material_lst'),true);
        return success($data ? $data : []);
    }



    public function setPrintStyle()
    {
        $mainDo = input('data');
        if(!is_array($mainDo) || !count($mainDo)){
            throw new ValidateException('请添加印刷方式');
        }

        app()->make(SystemConfigValueRepository::class)->setFormData(['sys_print_style_lst'=>join(',',$mainDo)],'admin');
        return success('保存成功');
    }


    public function getPrintStyle()
    {
        $data = systemConfig('sys_print_style_lst');
        return success($data ? explode(',',$data) : []);
    }







    // 案件类型配置
    public function setCaseType()
    {
        $mainDo = input('data');
        if(!is_array($mainDo) || !count($mainDo)){
            throw new ValidateException('请添加案件类型');
        }

        app()->make(SystemConfigValueRepository::class)->setFormData(['lawyer_case_type'=>join(',',$mainDo)],'admin');
        return success('保存成功');
    }


    public function getCaseType()
    {
        return success(explode(',',systemConfig('lawyer_case_type')));
    }


    public function set_article_agreement()
    {
        $mainDo = input('data');
        if(!is_array($mainDo) || !count($mainDo)){
            throw new ValidateException('请添加协议类型');
        }

        app()->make(SystemConfigValueRepository::class)->setFormData(['lawyer_article_agreement'=>join(',',$mainDo)],'admin');
        return success('保存成功');
    }


    public function get_article_agreement()
    {
        return success(explode(',',systemConfig('lawyer_article_agreement')));
    }




    public function getSwiper()
    {
        [$page,$limit] = $this->request->page();

        $count = app()->make(SystemSwiperRepository::class)->getSearch()->count();
        $list = app()->make(SystemSwiperRepository::class)->getSearch()->page($page,$limit)->select();

        return success(compact('count','list'));
    }

    public function getSwiperAll()
    {
        $count = app()->make(SystemSwiperRepository::class)->getSearch()->count();
        $list = app()->make(SystemSwiperRepository::class)->getSearch()->select();

        return success(compact('count','list'));
    }


    public function createSwiper()
    {
        app()->make(SystemSwiperRepository::class)->create($this->swiperCheckParam());
        return success('保存成功');
    }


    public function swiperCheckParam()
    {
        $params = $this->request->params(['title','pic','content']);
        $this->validate($params,[
           'title|标题'=>'require',
           'pic|图片'=>'require',
           'content|内容'=>'require',
        ]);

        return $params;
    }



    public function updateSwiper($id)
    {
        $data =  app()->make(SystemSwiperRepository::class)->get($id);
        if(!$data)
            return fail('数据不存在');
        $data->save($this->swiperCheckParam());
        return success('保存成功');
    }



    public function deleteSwiper($id)
    {
        $data =  app()->make(SystemSwiperRepository::class)->get($id);
        if(!$data)
            return fail('数据不存在');
        $data->delete();
        return success('删除成功');
    }


    public function detailSwiper($id)
    {
        $data =  app()->make(SystemSwiperRepository::class)->get($id);
        if(!$data)
            return fail('数据不存在');
        return success($data);
    }


















}